package com.zscat.mallplus.qsg.impl;

import com.alibaba.fastjson.JSONObject;
import com.zscat.mallplus.vo.CountDownObj;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@Slf4j
public class GetMqttDataValueCallable implements Callable<Integer> {

    private String deviceCode;

    private MqttConfigService mqttConfigService;

    GetMqttDataValueCallable(String deviceCode,MqttConfigService mqttConfigService){
        this.deviceCode = deviceCode;
        this.mqttConfigService = mqttConfigService;
    }

    @Override
    public Integer call() throws Exception {
        //mqtt客户端发送数据检查锁球器的球是否归为
        log.info("开始进行称重检查.");
        check(deviceCode);
        CountDownLatch countDownLatch = new CountDownLatch(1);
        ConcurrentHashMap<String, CountDownObj> countDownLatchMap = ChannelMap.getChannelMap();
        countDownLatchMap.putIfAbsent(deviceCode, new CountDownObj(countDownLatch));
        //阻塞，超时时间3s
        countDownLatch.await(5, TimeUnit.SECONDS);
        //返回mqtt指令对应的结果或者null
        return countDownLatchMap.remove(deviceCode).getValue();
    }

    private void check(String deviceCode) throws Exception {
        log.info("发送称重检查命令给mqtt服务器.");
        JSONObject dataInfo = new JSONObject();
        JSONObject headerInfo = new JSONObject();
        JSONObject bodyInfo = new JSONObject();
        headerInfo.put("Code","1004");
        headerInfo.put("Time", System.currentTimeMillis());
        headerInfo.put("Sign","lvzaina");
        dataInfo.put("Header",headerInfo);
        bodyInfo.put("MsgId",1683557943);
        bodyInfo.put("Cmd","Check");
        bodyInfo.put("Mode",1);
        dataInfo.put("Body",bodyInfo);
        mqttConfigService.subscribe("topic/pub/"+ deviceCode, 1);
        mqttConfigService.publish("topic/receive/"+ deviceCode, dataInfo.toJSONString());
    }
}
